package dbu.dbase.version3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import dbu.dbase.DBaseStructure;
import dbu.dbase.DataTypes;

public class MdxTagEntry extends DBaseStructure {

	/** Tag header page no. */
	private int page;

	/** Tag name */
	private String tagName;

	/** Key format: 00h - Calculated; 10h - Data field */
	private byte format;

	/** Forward tag thread lo */
	private byte lo;

	/** Forward tag thread hi */
	private byte hi;

	/** Backward tag thread */
	private byte back;

	/** Key type: C - Character; N - Numerical; D - Date */
	private DataTypes type;

	/**
	 * Read  
	 * @param stream
	 * @throws IOException
	 */
	@Override
	protected int read(InputStream stream) throws IOException {
		/** 4 bytes */
		page = readInt(stream);
		/** 11 bytes */
		tagName = readString(stream, 11);
		/** 1 byte */
		format = readByte(stream);
		/** 1 byte */
		lo = readByte(stream);
		/** 1 byte */
		hi = readByte(stream);
		/** 1 byte */
		back = readByte(stream);
		/** 1 byte 	Reserved */
		readByte(stream);
		/** 1 byte */
		type = DataTypes.getBySymbol((char) stream.read());
		/** 11 bytes	Reserved */
		stream.read(new byte[11]);

		return 32;
	}

	/**
	 * Write 
	 * @param stream
	 * @throws IOException
	 */
	protected void write(OutputStream stream) throws IOException {
		/** 4 bytes */
		stream.write(page);
		/** 11 bytes */
		writeString(stream, tagName, 11);
		/** 1 byte */
		stream.write(format);
		/** 1 byte */
		stream.write(lo);
		/** 1 byte */
		stream.write(hi);
		/** 1 byte */
		stream.write(back);
		/** 1 byte	Reserved */
		stream.write(new byte[] {0});
		/** 1 byte */
		stream.write(type.getSymbol());
		/** 11 bytes	Reserved */
		stream.write(new byte[11]);
	}

	@Override
	public String toString() {
		StringBuffer result = new StringBuffer();
		result.append("page:    "); result.append(page); result.append("\n");
		result.append("tagName: "); result.append(tagName); result.append("\n");
		result.append("format:  "); result.append(format); result.append("\n");
		result.append("lo:      "); result.append(lo); result.append("\n");
		result.append("hi:      "); result.append(hi); result.append("\n");
		result.append("back:    "); result.append(back); result.append("\n");
		result.append("type:    "); result.append(type); result.append("\n");
		return result.toString();
	}
}
